package network_programming.np1_socket_and_serversocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemoReceiver {
    private int port = 8081;
    private ServerSocket serverSocket;
    private static int stopWay = 1;         // 结束通信的方式
    private final int NATURAL_STOP = 1;     // 自然结束
    private final int SUDDEN_STOP = 2;      // 突然终止程序
    private final int SOCKET_STOP = 3;      // 关闭Socket，再结束程序
    private final int INPUT_STOP = 4;      // 关闭输出流，再结束程序
    private final int SERVERSOCKET_STOP = 5;    // 关闭ServerSocket，再结束程序
    public SocketDemoReceiver() throws IOException {
        serverSocket = new ServerSocket(port);
    }
    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIS = socket.getInputStream();     // 获取socket对象的输入流对象
        return new BufferedReader(new InputStreamReader(socketIS));
    }
    public void receive() throws IOException {
        Socket socket = null;
        socket = serverSocket.accept();
        BufferedReader br = getReader(socket);
        for(int i = 0; i < 20; i++) {
            String msg = br.readLine();
            System.out.println(msg);
            if(i == 2) {    // 终止程序，结束通信
                if(stopWay == SUDDEN_STOP) {
                    System.out.println("突然终止程序");
                    System.exit(0);
                }
                else if(stopWay == SOCKET_STOP) {
                    System.out.println("关闭Socket并结束程序");
                    socket.close();
                    break;
                }
                else if(stopWay == INPUT_STOP) {
                    System.out.println("关闭输入流并结束程序");
                    socket.shutdownInput();
                    break;
                }
                else if(stopWay == SERVERSOCKET_STOP) {
                    System.out.println("关闭ServerSocket并结束程序");
                    serverSocket.close();
                    break;
                }
            }
        }
        if(stopWay == NATURAL_STOP) {
            socket.close();
            serverSocket.close();
        }
    }

    public static void main(String[] args) throws IOException {
        if(args.length > 0)
            stopWay = Integer.parseInt(args[0]);
        new SocketDemoReceiver().receive();
    }
}
